"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Suspense } from 'react';
import { API_CONFIG } from "../url";
interface ApiResponse {
  id?: string;
  message?: string;
  [key: string]: any;
}

function FormContent() {
  const router = useRouter();
  const [showModal, setShowModal] = useState(false);
  const [modalMessage, setModalMessage] = useState("");
  const [countdown, setCountdown] = useState(0);
  const [isLoading, setIsLoading] = useState<boolean>(false);

  const showErrorModal = (message: string) => {
    setModalMessage(message);
    setShowModal(true);
  };

  const [formData, setFormData] = useState({
    telephone: "",
    code: "",
  });

  // 发送验证码（保持不变）
  const sendVerificationCode = async () => {
    if (!formData.telephone) {
      showErrorModal("请输入手机号码");
      return;
    }

    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(formData.telephone)) {
      showErrorModal("请输入正确的手机号码");
      return;
    }

    try {
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) clearInterval(timer);
          return prev - 1;
        });
      }, 1000);
      
      // 修改为正确的 GET 请求格式，参数通过 URL 传递
      // const response = await fetch(`http://localhost:8080/sms/send?phone=${formData.telephone}`, {
        const response = await fetch(`${API_CONFIG.BASE_URL}/api/sms/send?phone=${formData.telephone}`, {
        // const response = await fetch(`http://192.168.1.173:8080/sms/send?phone=${formData.telephone}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',

      });

      if (!response.ok) {
        throw new Error('发送验证码失败');
      }

      showErrorModal("验证码已发送");
    } catch (error) {
      console.error('发送验证码错误:', error);
      showErrorModal("发送验证码失败，请重试");
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { id, value } = e.target;
    setFormData(prev => ({ ...prev, [id]: value }));
  };

  
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    console.log("请求数据:", formData);
  
    // 验证输入
    if (!formData.telephone) {
      showErrorModal("请输入手机号");
      return;
    }
  
    if (!formData.code) {
      showErrorModal("请输入验证码");
      return;
    }
  
    try {
      setIsLoading(true);
      
      // 1. 调用登录接口
      const loginResponse = await fetch(
        `${API_CONFIG.BASE_URL}/api/login/teacher?phone=${formData.telephone}&code=${formData.code}`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          credentials: 'include',
        }
      );
    
      const responseText = await loginResponse.text();
      let loginResult;
      try {
        loginResult = JSON.parse(responseText);
      } catch (e) {
        loginResult = { message: responseText };
      }
    
      console.log('登录接口返回数据:', loginResult);
    
      if (!loginResponse.ok) {
        throw new Error(loginResult.message || `登录失败，状态码: ${loginResponse.status}`);
      }
  
      // 检查必要字段（根据实际接口调整）
      // const userId = loginResult.id || loginResult.userId || loginResult.data?.id;
      const token = loginResult.token || loginResult.accessToken || loginResult.data?.token;
      console.log("token1111",token)
  
      if (!token) {
        console.error('接口返回数据缺少必要字段:', loginResult);
        throw new Error('登录失败: 接口返回数据格式不正确');
      }
  
      // 存储用户信息和token
      // localStorage.setItem('userId', userId);
      localStorage.setItem('token', token);
      localStorage.setItem('userPhone', formData.telephone);
  
      // 2. 使用token获取用户详细信息
      const response = await fetch(
        // `http://localhost:8080/api/current/userInfo`,
         `${API_CONFIG.BASE_URL}/api/current/userInfo`,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          credentials: 'include',

        }
      );
  
    //  检查响应状态
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
  
      const result = await response.json();
      console.log("result",result)
  
     // 检查返回数据是否有效
     if (result && result.id) {
      // 存储用户ID到localStorage，键名为 "tid"
      localStorage.setItem("tid", result.id.toString()); // 确保存入的是字符串
      localStorage.setItem("parentLevel", result.parentLevel.toString()); 

      // 根据 personLevel 决定跳转页面
      if (result.parentLevel == 3) {
        setTimeout(() => {
          router.push(`/stuquery/stuquery1`);
        }, 1500);
      } else {
        setTimeout(() => {
          router.push(`/teaquery`);
        }, 1500);
      }
      } else {
        // 如果返回的数据中没有id，则认为用户不存在
        showErrorModal("用户不存在");
      }
    } catch (error) {
      console.error('登录流程错误:', error);
      showErrorModal((error as Error).message || "登录失败，请重试");
    }finally {
      setIsLoading(false);
    }
  };

  return (
    <main className="min-h-screen">
      <section className="py-20 pt-8">
        <div className="container mx-auto px-4">
          <div className="max-w-3xl mx-auto">
            <div className="bg-white rounded-lg shadow-sm p-8">
              <form className="space-y-6" onSubmit={handleLogin}>
                <div className="flex items-center">
                  <label htmlFor="telephone" className="block text-sm font-medium mb-2 mr-4 w-20">
                    手机号 <span className="text-red-600">*</span>
                  </label>
                  <input
                    type="text"
                    id="telephone"
                    className="px-4 py-2 border rounded-md flex-grow"
                    placeholder="请输入手机号"
                    required
                    onChange={handleInputChange}
                    value={formData.telephone}
                    maxLength={11}
                  />
                </div>

                <div className="flex items-center">
                  <label htmlFor="code" className="block text-sm font-medium mb-2 mr-4 w-20">
                    验证码 <span className="text-red-600">*</span>
                  </label>
                  <div className="flex flex-grow gap-2">
                    <input
                      type="text"
                      id="code"
                      className="px-4 py-2 border rounded-md flex-1"
                      placeholder="请输入验证码"
                      onChange={handleInputChange}
                      value={formData.code}
                      maxLength={4}
                    />
                    <button
                      type="button"
                      onClick={sendVerificationCode}
                      disabled={countdown > 0}
                      className={`px-4 py-2 rounded-md whitespace-nowrap ${countdown > 0
                        ? 'bg-gray-300 text-gray-500'
                        : 'bg-blue-600 text-white hover:bg-blue-700'
                        }`}
                    >
                      {countdown > 0 ? `${countdown}秒` : '获取验证码'}
                    </button>
                  </div>
                </div>

                <div className="flex">
                  <button
                    type="submit"
                    disabled={isLoading}
                    className="w-full bg-primary text-white py-2 rounded-md hover:bg-primary/90 disabled:opacity-50"
                  >
                    {isLoading ? '登录中...' : '登录'}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </section>

      {showModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 max-w-md w-full">
            <p className="mb-6">{modalMessage}</p>
            <div className="flex justify-end">
              <button
                onClick={() => setShowModal(false)}
                className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
              >
                确定
              </button>
            </div>
          </div>
        </div>
      )}
    </main>
  );
}

export default function CertificatesPage() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <FormContent />
    </Suspense>
  );
}